const Model = require('./models');
const express = require('express');
const router = express.Router();
const Mock = require('mockjs');
const moment = require('moment');

// 注册-用法同添加新用户路由：/user-add
// router.post('/register',async(req,res) => {
//     
// });

//获取用户列表
router.get('/user', async(req,res) => {
  var responses = await Model.User.findAll();
  var output = [];
  responses.forEach(response => {
    if (response.Permission != '管理员') {
      var data = {
        id: response.Id,
        username: response.UserName,
        userpwd: response.UserPass,
        userrole: response.Permission
      }
      output.push(data);
    }
  });
  res.send(output);
});
//更新一个用户
router.put('/user-edit', async(req,res) => {
  await Model.User.update({
    UserName: req.body.username,
    UserPass: req.body.userpwd,
    Permission: req.body.userrole
  }, {
    where: {
      Id: req.body.id
    }
  }).then(response => {
    res.send({
      code: 200,
      data: 'update successfully.'
    });
  }).catch(e => {
    res.send({
      code: 400,
      data: e
    });
  });
});
//添加一个用户
router.post('/user-add', async(req,res) => {
  await Model.User.create({
      UserName: req.body.username,
      UserPass: req.body.userpwd,
      Permission: req.body.userrole
    }).then(response => {
      res.send({
        code: 200,
        data: 'insert successfully.'
      });
    }).catch(e => {
      res.send({
        code: 400,
        data: e
      });
    });
});
//删除一个用户
router.delete('/user-delete', async(req,res) => {
  await Model.User.destroy({
    where: {
      Id : req.query.id
    }
  }).then(response => {
    res.send({
      code: 200,
      data: 'delete successfully.'
    });
  }).catch(e => {
    res.send({
      code: 400,
      data: e
    });
  });
});
// 登陆
router.get('/login',async(req,res) => {
    var response = await Model.User.findAll({
        where: {
            UserName: req.query.username,
            UserPass: req.query.password
        }
    });
    // 先判断用户是否存在
    if (response.length != 0) {
      var now = new Date();
      // 写入登陆信息
      const loginUser = await Model.LoginInfo.findOne({
        where: {
          UserId: response[0].dataValues.Id
        }
      });
      if (loginUser) {
        await Model.LoginInfo.update({
          LoginDate: now.toLocaleString('zh'),
        }, {
          where: {
            UserId: response[0].dataValues.Id,
          }
        });
      } else {
        await Model.LoginInfo.create({
          UserId: response[0].dataValues.Id,
          LoginDate: now.toLocaleString('zh'),
          Remark: response[0].dataValues.Permission
        });
      }
      
      var loginInfo = {
        loginTime: now.toLocaleString('zh'),
        userName: response[0].dataValues.UserName,
        userPermission: response[0].dataValues.Permission
      }
      // 判断权限
      if (response[0].dataValues.Permission === '管理员') {
        res.send({
          code: 20000,
          data: {
            loginData: loginInfo,
            menu: [
              {
                path: '/',
                name: 'home',
                label: '首页',
                icon: 's-home',
                url: 'Home/Home'
              },
              {
                path: '/consumemoney',
                name: 'consumemoney',
                label: '金额消费',
                icon: 's-shop',
                url: 'Consume/ConsumeMoney'
              },
              {
                path: '/consumecard',
                name: 'consumecard',
                label: '划卡消费',
                icon: 's-marketing',
                url: 'Consume/ConsumeCard'
              },
              {
                label: '其他功能',
                icon: 'location',
                children: [
                  {
                    path: '/setting',
                    name: 'setting',
                    label: '设置',
                    icon: 'setting',
                    url: 'Others/Setting'
                  },
                  {
                    path: '/info',
                    name: 'info',
                    label: '其他',
                    icon: 'info',
                    url: 'Others/Info'
                  }
                ]
              },
              {
                path: '/customer',
                name: 'customer',
                label: '会员管理',
                icon: 'video-play',
                url: 'CustomerManage/CustomerManage'
              },
              {
                path: '/user',
                name: 'user',
                label: '用户管理',
                icon: 'user',
                url: 'UserManage/UserManage'
              }
            ],
            token: Mock.Random.guid(),
            message: '获取成功'
          }
        });
      } else if (response[0].dataValues.Permission === '收银员') {
        res.send({
          code: 20000,
          data: {
            loginData: loginInfo,
            menu: [
              {
                path: '/',
                name: 'home',
                label: '首页',
                icon: 's-home',
                url: 'Home/Home'
              },
              {
                path: '/consumemoney',
                name: 'consumemoney',
                label: '金额消费',
                icon: 's-shop',
                url: 'Consume/ConsumeMoney'
              },
              {
                path: '/consumecard',
                name: 'consumecard',
                label: '划卡消费',
                icon: 's-marketing',
                url: 'Consume/ConsumeCard'
              },
              {
                label: '其他功能',
                icon: 'location',
                children: [
                  {
                    path: '/setting',
                    name: 'setting',
                    label: '销售',
                    icon: 'setting',
                    url: 'Others/Setting'
                  }
                ]
              },
              {
                path: '/customer',
                name: 'customer',
                label: '会员管理',
                icon: 'video-play',
                url: 'CustomerManage/CustomerManage'
              }
            ],
            token: Mock.Random.guid(),
            message: '获取成功'
          }
        });
      }
    } else {
        res.send({
            code: -999,
            data: {
            message: '用户不存在'
            }
      });
    }
});

// 获取会员消费金额
router.get('/amount', async(req,res) => {
  var responses = await Model.Consume.findAll({
    limit: 100
  });
  var output = [];
  responses.forEach(response => {
    var data = {
      name: response.Customer_Name,
      amount: response.Amount,
      amountType: response.AmountType,
      amountDate: response.AmountDate.toLocaleString('zh')
    };
    output.push(data);
  });
    
  res.send(output);
});

// 插入消费记录
router.post('/amount-create',async(req,res) => {
  var insertData = {
    Id: null,
    Customer_Id: req.body.id,
    Customer_Name: req.body.name,
    Amount: req.body.amount,
    AmountType: req.body.radioChecked,
  }
  await Model.Consume.create(insertData).then(response => {
    res.send({
      code: 200,
      data: 'create consume successfully.'
    });
  }).catch(e => {
    res.send({
      code: 400,
      data: e
    });
  });
});

// 创建会员
router.post('/customer-create',async(req,res) => {
    var insertData = {
        Id: null,
        CustomerNum: req.body.CustomerPhone,
        CustomerName: req.body.CustomerName,
        CustomerPhone: req.body.CustomerPhone,
        CustomerLevel: req.body.CustomerLevel,
    }
    await Model.Customer.create(insertData).then(response => {
      res.send({
        code: 200,
        data: 'create customer successfully.'
      });
    }).catch(e => {
      res.send({
        code: 400,
        data: e
      });
    });
});
// 删除会员
router.delete('/customer-delete',async(req,res) => {
  await Model.Customer.destroy({
    where: {
      Id : req.query.id
    }
  }).then(response => {
    res.send({
      code: 200,
      data: 'delete customer successfully.'
    });
  }).catch(e => {
    res.send({
      code: 400,
      data: e
    });
  });
});

//更新会员
router.put('/customer-edit',async(req,res) => {
  var now = new Date();
  await Model.Customer.update({
    CustomerName: req.body.CustomerName,
    CustomerPhone: req.body.CustomerPhone,
    CustomerLevel: req.body.CustomerLevel,
    UpdateDate: now.toLocaleString('zh')
  }, {
    where: {
      Id: req.body.Id
    }
  }).then(response => {
    res.send({
      code: 200,
      data: 'update customer successfully.'
    });
  }).catch(e => {
    res.send({
      code: 400,
      data: e
    });
  });
});
// 查询所有会员
router.get('/customer-list',async(req,res) => {
    await Model.Customer.findAll({}).then(response => {
      res.send({
        code: 200,
        data: response
      });
    }).catch(e => {
      res.send({
        code: 400,
        data: e
      });
    });
});
// 查询一个会员
router.get('/customer-get-one',async(req,res) => {
  await Model.Customer.findAll({
    where: {
      CustomerNum: req.query.customerNum
    }
  }).then(response => {
    res.send({
      code: 200,
      data: response
    });
  }).catch(e => {
    res.send({
      code: 400,
      data: e
    });
  });
});
// 创建次卡
router.post('/card-operate',async(req,res) => {
  if (req.body.radioChecked == '开卡') {
    var insertData = {
      Id: null,
      CardNum: req.body.num,
      CardName: req.body.categoryChecked,
      AllFrequency: req.body.allfrequency,
      UsedFrequency: 0,
      SurplusFrequency: req.body.allfrequency,
    }
    var record = await Model.Card.findOne({
      where: {
        CardNum: req.body.num
      }
    });
    if (!record) {
      await Model.Card.create(insertData).then(response => {
        res.send({
          code: 200,
          message: '开卡成功！'
        });
      }).catch(e => {
        res.send({
          code: 400,
          message: '开卡失败！'
        });
      });
    } else {
      res.send({
        code: 300,
        message: '此卡已存在！'
      });
    }
  } else if (req.body.radioChecked == '核销') {
    try {
      var card = await Model.Card.findOne({
        where: {
          CardNum: req.body.num
        }
      });
      if (card) {
        if (card.SurplusFrequency > 0) {
          await Model.CardConsume.create({
            Id: null,
            CardNum: req.body.num,
            CardName: req.body.name,
            CardAmount: 1,
          });
          await Model.Card.update({
            UsedFrequency: card.UsedFrequency + 1,
            SurplusFrequency: card.SurplusFrequency - 1,
            HandleDate: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
          }, {
            where: {
              CardNum: req.body.num
            }
          });
          res.send({
            code: 200,
            message: '核销成功！'
          });
        } else {
          res.send({
            code: 300,
            message: '次数已用完！'
          });
        }
      } else {
        res.send({
          code: 300,
          message: '此卡不存在！'
        });
      }
      
      // If the execution reaches this line, no errors were thrown.
      // We commit the transaction.

    } catch (error) {
      // If the execution reaches this line, an error was thrown.
      // We rollback the transaction.
    }
  }
});
// 查询一张次数卡
router.get('/card-get-one',async(req,res) => {
  await Model.Card.findAll({
    where: {
      CardNum: req.query.cardNum
    }
  }).then(response => {
    res.send({
      code: 200,
      data: response
    });
  }).catch(e => {
    res.send({
      code: 400,
      data: e
    });
  });
});
module.exports = router;